package top.angular2;

import sun.applet.Main;

import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Calendar;

/**
 * @deprecated 把简书的文件转换成hexo支持的格式
 * 主要是增加标题，时间，作者等信息
 * <p>
 * 增加后的样式如下：
 * ---
 * title: 标题
 * date: 时间 2017-11-13 15:11:25
 * categories: 分类
 * ---
 */
public class ChangeMD {
    private static final String PATH = "E:\\md";//简书打包下载的文件路径

    public static void main(String[] args) {
//        test();
        change();
//        try {
//            fileAppender("E:\\test.md","kanshenmekan    ");
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
    }

    private static void change() {
        String title = ""; // 标题
        String date = ""; //时间
        String categories = ""; //分类


        //读取文件
        File file = new File(PATH);
        if (!file.exists() || !file.isFile()) {
            System.out.println("文件不存在或者文件类型不正确");
        }
        if (file.isDirectory()) {
            File[] files = file.listFiles();
            for (File f : files) {
                // 记录文件夹名称为 分类
                categories = f.getName();
                if (f.isDirectory()) {
                    File[] fs = f.listFiles();
                    for (File f1 : fs) {
                        StringBuilder str = new StringBuilder();
                        // 记录文件名为 标题
                        title = f1.getName().replace(".md","");
                        // 记录文件创建时间
                        date = getCreateTime(f.getAbsolutePath());
                        if(date == null){
                          date = getModifiedTime_2(f.getAbsolutePath());
                        }

                        str.append("---");
                        str.append("\r\ntitle: " + title);
                        str.append("\r\ndate: " + date);
                        str.append("\r\ncategories: " + categories);
                        str.append("\r\n---\r\n");
//                        System.out.println(str);
//                        System.out.println("");
//                        System.out.println("");
//                        System.out.println("");
                        try {
                            fileAppender(f1.getAbsolutePath(),str.toString());
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        }
    }

    private static void test() {
        File f = new File("E:\\test.md");

        try {
            BufferedReader br = new BufferedReader(new FileReader("E:\\test.md"));
            String s = "";
            StringBuilder st = new StringBuilder();
            while (( s = br.readLine()) != null) {
                st.append(s);
            }
            System.out.println(st.toString());

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        String title = "标题"; // 标题
        String date = "时间"; //时间
        String categories = "分类"; //分类
        StringBuilder str = new StringBuilder();
        str.append("\r\n ---");
        str.append("\r\n title: " + title);
        str.append("\r\n date: " + date);
        str.append("\r\n categories: " + categories);
        str.append("\r\n --- \r\n  ");
        System.out.println(str);
        System.out.println("");

        BufferedWriter bw = null;
        try {
            bw = new BufferedWriter(new FileWriter(f));
            bw.write(String.valueOf(str));
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                bw.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }

    /**
     * 在文件前面追加文件内容
     */
    public static void fileAppender(String fileName, String contents)
            throws IOException {
        BufferedReader reader = new BufferedReader(new FileReader(fileName));
        String line = null;
        // 一行一行的读
        StringBuilder sb = new StringBuilder();
        sb.append(contents);
        while ((line = reader.readLine()) != null) {
            sb.append(line);
            sb.append("\r\n");
        }
        reader.close();

        //写回去
        BufferedWriter bw = null;
        try {
            bw = new BufferedWriter(new FileWriter(fileName));
            bw.write(String.valueOf(sb));
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                bw.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
//        RandomAccessFile write = new RandomAccessFile(fileName, "rw");
//        write.writeBytes(sb.toString()); //<---会产生中文乱码
//        write.close();
    }


    //配置信息

    //输出文件


    /**
     * 读取文件创建时间
     */
    public static String getCreateTime(String filePath) {
//            String filePath = "D:\\t.txt";
        String strTime = null;
        try {
            Process p = Runtime.getRuntime().exec("cmd /C dir "
                    + filePath
                    + "/tc");
            InputStream is = p.getInputStream();
            BufferedReader br = new BufferedReader(new InputStreamReader(is));
            String line;
            while ((line = br.readLine()) != null) {
                if (line.endsWith(".txt")) {
                    strTime = line.substring(0, 17);
                    break;
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
//            System.out.println("创建时间    " + strTime);//输出：创建时间   2009-08-17  10:21
        return strTime;
    }

    /**
     * 读取文件修改时间的方法1
     */
    @SuppressWarnings("deprecation")
    public static void getModifiedTime_1() {
        File f = new File("C:\\test.txt");
        Calendar cal = Calendar.getInstance();
        long time = f.lastModified();
        cal.setTimeInMillis(time);
        //此处toLocalString()方法是不推荐的，但是仍可输出
        System.out.println("修改时间[1] " + cal.getTime().toLocaleString());
        //输出：修改时间[1]    2009-8-17 10:32:38
    }

    /**
     * 读取修改时间的方法2
     */
    public static String getModifiedTime_2(String path) {
        File f = new File(path);
        Calendar cal = Calendar.getInstance();
        long time = f.lastModified();
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        cal.setTimeInMillis(time);
        return  formatter.format(cal.getTime());
//        System.out.println("修改时间[2] " + formatter.format(cal.getTime()));
        //输出：修改时间[2]    2009-08-17 10:32:38
    }

}
